import 'package:bilibili/http/dao/ranking_dao.dart';
import 'package:bilibili/widget/hi_tab_bar.dart';
import 'package:bilibili/widget/navigation_bar.dart';
import 'package:bilibili/widget/video_detail_card.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

import '../http/model/ranking_mo.dart';
import '../http/model/video_model.dart';
import '../util/view_utils.dart';

class RankingPage extends StatefulWidget {
  const RankingPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _RankingPageState();
  }
}

class _RankingPageState extends State<RankingPage>
    with TickerProviderStateMixin {
  final TABS = [
    {"key": "like", "name": "最热"},
    {"key": "pubdate", "name": "最新"},
    {"key": "favorite", "name": "收藏"}
  ];

  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: TABS.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [_buildNavigatorBar(), _buildTabPageView()],
      ),
    );
  }

  _buildNavigatorBar() {
    return context.commonStatusBar(
        child: Container(
      decoration: bottomBoxShadow(context),
      child: HiTabBar(
          controller: _tabController,
          tabs: TABS.map((element) {
            return Tab(
              text: element["name"],
            );
          }).toList()),
    ));
  }

  _buildTabPageView() {
    return Flexible(
        child: TabBarView(
      controller: _tabController,
      children: TABS.map((element) {
        var key = element["key"] as String;
        return _InnerPage(keyWord: key);
      }).toList(),
    ));
  }
}

class _InnerPage extends StatefulWidget {
  final String keyWord;

  const _InnerPage({super.key, required this.keyWord});

  @override
  State<StatefulWidget> createState() {
    return _InnerPageState();
  }
}

class _InnerPageState extends State<_InnerPage> {
  bool _isLoading = false;
  final List<VideoModel> videoList = List.empty(growable: true);
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_loadMore);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  void _loadMore() {
    if (_scrollController.position.pixels ==
            _scrollController.position.maxScrollExtent &&
        !_isLoading) {
      setState(() {
        _isLoading = true;
      });

      // _loadData(loadMore: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder(
            future: _loadData(loadMore: _isLoading),
            builder: (BuildContext context,
                AsyncSnapshot<List<VideoModel>> snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                var data = snapshot.data;
                if (data == null) {
                  return const Center(
                    child: Text("没有数据"),
                  );
                }
              } else {
                if (!_isLoading) {
                  return Lottie.asset("assets/loading.json");
                }
              }
              return _buildList(videoList);
            }));
  }

  var currentPageIndex = 1;
  var pageSize = 10;
  var isEnd = false;

  Future<List<VideoModel>> _loadData({bool loadMore = false}) async {
    if (loadMore && !isEnd) {
      currentPageIndex++;
    }

    RankingMo data = await RankingDao.get(widget.keyWord,
        pageIndex: currentPageIndex, pageSize: pageSize);
    if (!isEnd) {
      videoList.addAll(data.list);
    }
    if (data.list.length < pageSize) {
      isEnd = true;
    }
    return videoList;
  }

  Widget _buildList(List<VideoModel> data) {
    return ListView.separated(
        controller: _scrollController,
        padding: const EdgeInsets.only(left: 15, right: 15, top: 10),
        separatorBuilder: (BuildContext context, int index) => const Divider(),
        itemCount: _isLoading ? data.length + 1 : data.length,
        itemBuilder: (BuildContext context, int index) {
          if (index == data.length) {
            if (isEnd) {
              return _loadEnd();
            } else {
              //加载更多
              return loadMore();
            }
          }
          var videoModel = data[index];
          return VideoDetailCard(videoModel);
        });
  }

  Widget _loadEnd() {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Text("没有更多了！"),
      ),
    );
  }
}
